package com.asiainfo.heshanghui.networkModel;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.asiainfo.heshanghui.configs.ConstantsME;
import com.asiainfo.heshanghui.entity.GoodsTypeInfo;
import com.asiainfo.heshanghui.entity.IdsInfo;
import com.asiainfo.heshanghui.entity.SaleListInfo;
import com.asiainfo.heshanghui.entity.ScanInfo;
import com.asiainfo.heshanghui.entity.StoreInfo;
import com.framework.Utils.JSONParseUtil;
import com.framework.Utils.PreferencesHelper;
import com.framework.Utils.Y;
import com.framework2.base.BiuooBaseActivity;
import com.framework2.okhttp3.HandlerCallback;
import com.framework2.okhttp3.Ok3Util;
import com.framework2.okhttp3.StringRequest;
import com.asiainfo.heshanghui.configs.InterfaceConfig;
import com.framework2.utils.BiuooCollectionUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;

/**
 * HttpUtil
 *
 * @author Yangjie
 *         className GohomePopupWindowUtil
 *         created at  2017/3/17  13:01
 */
public class HttpUtil {
    private static volatile HttpUtil singleton;

    private HttpUtil() {
    }

    public static HttpUtil getInstance() {
        if (singleton == null) {
            synchronized (HttpUtil.class) {
                if (singleton == null) {
                    singleton = new HttpUtil();
                }
            }
        }
        return singleton;
    }

    private DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance();

    /**
     * 一般的返回
     */
    public interface OnRequestResult<T> {
        void onSuccess(T... t);

        void onFail(int code, String msg);
    }


    /**
     * 返回列表
     *
     * @param <T>
     */
    public interface OnRequestListResult<T> {
        void onSuccess(List<T> list, String... msg);

        void onFail(int code, String msg);
    }

    /**
     * 出库--查询IMEI
     */
    public void requestQueryQRcode(final BiuooBaseActivity baseActivity, String _interface, @NonNull final String shopId, @NonNull final String imei, final OnRequestResult<ScanInfo> resultListener) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("shopId", shopId);
            jsonObject.put("imeiNo", imei);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final StringRequest jsonRequest = StringRequest.getBuilder(false).url(InterfaceConfig.BASE_SERVER_URL + _interface).get(jsonObject)
                .build(new HandlerCallback() {
                    @Override
                    public void onResponseMainThread(Call call, String result) throws IOException {
                        if (null != resultListener) {
                            boolean success = ParseResponseUtil.getInstance().isSuccess(baseActivity, result);
                            String errorMsg = ParseResponseUtil.getInstance().parseReturnStringError(result);
                            String fullName = ParseResponseUtil.getInstance().parseReturnString(result, "fullName");
                            String brandName = ParseResponseUtil.getInstance().parseReturnString(result, "brandName");
                            String phoneType = ParseResponseUtil.getInstance().parseReturnString(result, "categoryId");
                            String suggestPrice = ParseResponseUtil.getInstance().parseReturnString(result, "suggestPrice");
                            String imgUrl = ParseResponseUtil.getInstance().parseReturnString(result, "smallMobileImgUrl");
                            String color = ParseResponseUtil.getInstance().parseReturnString(result, "color");
                            String room = ParseResponseUtil.getInstance().parseReturnString(result, "storageSize");
                            String purchasePrice = ParseResponseUtil.getInstance().parseReturnString(result, "storageSize");//入库单价
                            String goodsType = ParseResponseUtil.getInstance().parseReturnString(result, "storageSize");//型号
                            int remainQuantity = ParseResponseUtil.getInstance().parseReturnInt(result, "remainQuantity");
                            decimalFormat.applyPattern("0.00");
                            double _suggestPrice = 0;
                            try {
                                _suggestPrice = Double.parseDouble(suggestPrice);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (success && remainQuantity > 0) {
                                ScanInfo info = new ScanInfo();
                                info.setName(fullName);
                                info.setImei(imei);
                                info.setPrice(_suggestPrice);
                                info.setType(phoneType);
                                info.setImgUrl(imgUrl);
                                info.setContent(brandName);
                                info.setRoom(room);
                                info.setColor(color);
                                info.setIsPhone(true);
                                info.setPurchasePrice(purchasePrice);
                                info.setGoodsType(goodsType);
                                resultListener.onSuccess(info);
                            } else {
                                resultListener.onFail(1, "库存可能不存在该IMEI号");
                            }
                        }
                    }

                    @Override
                    public void onFailureMainThread(Call call, IOException e) {
                        if (null != resultListener) {
                            resultListener.onFail(0, e.getMessage());
                        }
                    }
                });
        Ok3Util.getInstance().setBuilder(new OkHttpClient.Builder().connectTimeout(8000, TimeUnit.MILLISECONDS).retryOnConnectionFailure(false)).addToRequestQueueAsynchoronous(jsonRequest);
    }


    /**
     * 仅查询我的店铺ids
     */
    public void requestJustShopIds(final BiuooBaseActivity baseActivity, String _interface, final OnRequestListResult<IdsInfo> resultListener) {
        StringRequest jsonRequest = StringRequest.getBuilder(true).url(InterfaceConfig.BASE_SERVER_URL + _interface).get()
                .build(new HandlerCallback() {
                    @Override
                    public void onResponseMainThread(Call call, String result) throws IOException {
                        if (null != resultListener) {
                            boolean success = ParseResponseUtil.getInstance().isSuccess(baseActivity, result);
                            String errorMsg = ParseResponseUtil.getInstance().parseReturnStringError(result);
                            if (success) {
                                JSONArray jsonArray = ParseResponseUtil.getInstance().parseReturnJSONArray(result);
                                if (null != jsonArray && jsonArray.length() > 0) {
                                    ArrayList<IdsInfo> list = new ArrayList<>();
                                    int lenth = jsonArray.length();
                                    for (int i = 0; i < lenth; i++) {
                                        JSONObject jsonObject = jsonArray.optJSONObject(i);
                                        if (null != jsonObject) {
                                            IdsInfo idsInfo = new IdsInfo();
                                            idsInfo.setShopId(JSONParseUtil.getInstance().optString(jsonObject, "shopId"));
                                            idsInfo.setCompanyId(JSONParseUtil.getInstance().optString(jsonObject, "companyId"));
                                            list.add(idsInfo);
                                        }
                                    }
                                    resultListener.onSuccess(list);
                                }
                            } else {
                                resultListener.onFail(1, errorMsg);
                            }
                        }
                    }

                    @Override
                    public void onFailureMainThread(Call call, IOException e) {
                        if (null != resultListener) {
                            resultListener.onFail(0, e.getMessage());
                        }
                    }
                });
        Ok3Util.getInstance().addToRequestQueueAsynchoronous(jsonRequest);
    }

    /**
     * 查询商品类型
     */
    public void requestGoodsTypeList(final BiuooBaseActivity baseActivity, final int position, String _interface, @NonNull final String shopId, @NonNull final String classId, @NonNull final String brandId,  @NonNull final String modelId,final OnRequestListResult<GoodsTypeInfo> resultListener) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("shopId", shopId);
            jsonObject.put("classId", classId);
            jsonObject.put("brandId", brandId);
            jsonObject.put("modelId", modelId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        StringRequest jsonRequest = StringRequest.getBuilder(true).url(InterfaceConfig.BASE_SERVER_URL + _interface).get(jsonObject)
                .build(new HandlerCallback() {
                    @Override
                    public void onResponseMainThread(Call call, String result) throws IOException {
                        if (null != resultListener) {
                            boolean success = ParseResponseUtil.getInstance().isSuccess(baseActivity, result);
                            String errorMsg = ParseResponseUtil.getInstance().parseReturnStringError(result);
                            if (success) {
                                JSONArray jsonArray = ParseResponseUtil.getInstance().parseReturnJSONArray(result);
                                if (null != jsonArray && jsonArray.length() > 0) {
                                    ArrayList<GoodsTypeInfo> list = new ArrayList<>();
                                    int lenth = jsonArray.length();
                                    for (int i = 0; i < lenth; i++) {
                                        JSONObject jsonObject = jsonArray.optJSONObject(i);
                                        if (null != jsonObject) {
                                            GoodsTypeInfo goodsTypeInfo = new GoodsTypeInfo();
                                            goodsTypeInfo.setId(JSONParseUtil.getInstance().optString(jsonObject, "classId"));
                                            goodsTypeInfo.setTitle(JSONParseUtil.getInstance().optString(jsonObject, "className"));
                                            if (position == 0) {
                                                goodsTypeInfo.setId(JSONParseUtil.getInstance().optString(jsonObject, "classId"));
                                                goodsTypeInfo.setTitle(JSONParseUtil.getInstance().optString(jsonObject, "className"));
                                            } else if (position == 1) {
                                                goodsTypeInfo.setId(JSONParseUtil.getInstance().optString(jsonObject, "brandId"));
                                                goodsTypeInfo.setTitle(JSONParseUtil.getInstance().optString(jsonObject, "brandName"));
                                            } else if (position == 2) {
                                                goodsTypeInfo.setId(JSONParseUtil.getInstance().optString(jsonObject, "modelId"));
                                                goodsTypeInfo.setTitle(JSONParseUtil.getInstance().optString(jsonObject, "modelName"));
                                            }
                                            list.add(goodsTypeInfo);
                                        }
                                    }
                                    resultListener.onSuccess(list);
                                }
                            } else {
                                resultListener.onFail(1, errorMsg);
                            }
                        }
                    }

                    @Override
                    public void onFailureMainThread(Call call, IOException e) {
                        if (null != resultListener) {
                            resultListener.onFail(0, e.getMessage());
                        }
                    }
                });
        Ok3Util.getInstance().addToRequestQueueAsynchoronous(jsonRequest);
    }
    /**
     * 出库--生成销售单
     */
    public void requestBuildSaleList(final BiuooBaseActivity baseActivity, String _interface, @NonNull final String shopId, @NonNull final String name, @NonNull final int contactType, @NonNull final String contact, @NonNull final String remark, List<SaleListInfo> saleInfoList, final OnRequestResult<String> resultListener) {
        HashMap<String, String> map = new HashMap<>();
        map.put("shopId", shopId);
        map.put("customerName", name);
        map.put("contactWay", contactType + "");
        map.put("customerLinktel", contact);
        map.put("remark", remark);
        JSONArray stockOutDetails = new JSONArray();
        try {
            int len = saleInfoList.size();
            for (int i = 0; i < len; i++) {
                SaleListInfo saleListInfo = saleInfoList.get(i);
                if (null != saleListInfo) {
                    boolean isPhone = TextUtils.equals("0", saleListInfo.getType());
                    ArrayList<ScanInfo> list = saleListInfo.getList();
                    if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
                        int listLen = list.size();
                        for (int j = 0; j < listLen; j++) {
                            ScanInfo scanInfo = list.get(j);
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("categoryId", TextUtils.isEmpty(scanInfo.getType()) ? "" : scanInfo.getType());
                            jsonObject.put("fullName", TextUtils.isEmpty(scanInfo.getName()) ? "" : scanInfo.getName());
                            jsonObject.put("imei", isPhone ? scanInfo.getImei() : "");//手机/配件
                            jsonObject.put("outboundPrice", scanInfo.getPrice());
                            jsonObject.put("productType", isPhone ? "1" : "2");
                            jsonObject.put("quantity", scanInfo.getCount());
                            jsonObject.put("remark", "");
                            stockOutDetails.put(jsonObject);
                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("stockOutDetails", stockOutDetails.toString());
        final StringRequest jsonRequest = StringRequest.getBuilder(false).url(InterfaceConfig.BASE_SERVER_URL + _interface).post(map)
                .build(new HandlerCallback() {
                    @Override
                    public void onResponseMainThread(Call call, String result) throws IOException {
                        if (null != resultListener) {
                            boolean success = ParseResponseUtil.getInstance().isSuccess(baseActivity, result);
                            String errorMsg = ParseResponseUtil.getInstance().parseReturnStringError(result);
                            String profit = ParseResponseUtil.getInstance().parseReturnString(result, "profit");
                            String orderCode = ParseResponseUtil.getInstance().parseReturnString(result, "orderNo");
                            String intro = ParseResponseUtil.getInstance().parseReturnString(result, "intro");
                            String date = ParseResponseUtil.getInstance().parseReturnString(result, "date");
                            if (success) {
                                resultListener.onSuccess(profit, orderCode, intro, date);
                            } else {
                                resultListener.onFail(1, errorMsg);
                            }
                        }
                    }

                    @Override
                    public void onFailureMainThread(Call call, IOException e) {
                        if (null != resultListener) {
                            resultListener.onFail(0, e.getMessage());
                        }
                    }
                });
        Ok3Util.getInstance().addToRequestQueueAsynchoronous(jsonRequest);
    }

    /**
     * 库存--库存列表
     */
    public void requestStoreList(final BiuooBaseActivity baseActivity, String _interface, @NonNull final String shopId,int type, @NonNull final String fullName, @NonNull final int page, @NonNull final int pageSize, final OnRequestListResult<StoreInfo> resultListener) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("shopId", shopId);
            jsonObject.put("fullName", fullName);
            jsonObject.put("pageNo", page);
            jsonObject.put("pageSize", pageSize);
            jsonObject.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final StringRequest jsonRequest = StringRequest.getBuilder(false).url(InterfaceConfig.BASE_SERVER_URL + _interface).get(jsonObject)
                .build(new HandlerCallback() {
                    @Override
                    public void onResponseMainThread(Call call, String result) throws IOException {
                        if (null != resultListener) {
                            boolean success = ParseResponseUtil.getInstance().isSuccess(baseActivity, result);
                            String errorMsg = ParseResponseUtil.getInstance().parseReturnStringError(result);
                            if (success) {
                                ArrayList<StoreInfo> list = new ArrayList<>();
                                JSONObject jsonObject = ParseResponseUtil.getInstance().parseReturnJSONObject(result);
                                if (null != jsonObject) {
                                    String totalRecords = JSONParseUtil.getInstance().optString(jsonObject, "totalRecords");
                                    JSONArray array = JSONParseUtil.getInstance().optJSONArray(jsonObject, "queryInventoryDetail");
                                    if (null != array && array.length() > 0) {
                                        int len = array.length();
                                        for (int i = 0; i < len; i++) {
                                            JSONObject jsonOb = array.optJSONObject(i);
                                            if (null != jsonOb) {
                                                StoreInfo info = new StoreInfo();
                                                info.setName(JSONParseUtil.getInstance().optString(jsonOb, "productName"));
                                                info.setImgUrl(JSONParseUtil.getInstance().optString(jsonOb, "bigMobileUrl"));
                                                info.setCount(JSONParseUtil.getInstance().optInt(jsonOb, "quantity"));
                                                try {
                                                    info.setPrice(Double.parseDouble(JSONParseUtil.getInstance().optString(jsonOb, "suggestUnitPrice")));
                                                } catch (NumberFormatException e) {
                                                    info.setPrice(0);
                                                }
                                                info.setProductType(JSONParseUtil.getInstance().optInt(jsonOb, "productType"));
                                                list.add(info);
                                            }
                                        }
                                    }
                                    resultListener.onSuccess(list, totalRecords);
                                } else {
                                    resultListener.onFail(0, errorMsg);
                                }
                            } else {
                                resultListener.onFail(1, errorMsg);
                            }
                        }
                    }

                    @Override
                    public void onFailureMainThread(Call call, IOException e) {
                        if (null != resultListener) {
                            resultListener.onFail(0, e.getMessage());
                        }
                    }
                });
        Ok3Util.getInstance().addToRequestQueueAsynchoronous(jsonRequest);
    }
    /**
     * 手机登录
     */
    public void requestLogin(String _interface, @NonNull String phone, @NonNull String pwd, final OnRequestResult<String> resultListener) {
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        map.put("password", pwd);
        StringRequest jsonRequest = StringRequest.getBuilder(false).url(InterfaceConfig.BASE_SERVER_URL + _interface).post(map)
                .build(new HandlerCallback() {
                    @Override
                    public void onResponseMainThread(Call call, String result) throws IOException {
                        Y.y("JSONRequestonResponse:" + result);
                        if (null != resultListener) {
                            boolean success = ParseResponseUtil.getInstance().isSuccess(result);
                            String token = ParseResponseUtil.getInstance().parseReturnString(result, "userKey");
                            String nickName = ParseResponseUtil.getInstance().parseReturnString(result, "nickName");
                            String headPicUrl = ParseResponseUtil.getInstance().parseReturnString(result, "headPicUrl");
                            String errorMsg = ParseResponseUtil.getInstance().parseReturnStringError(result);
                            if (success) {
                                if (!TextUtils.isEmpty(token)) {
                                    resultListener.onSuccess(token, nickName, headPicUrl);
                                } else {
                                    resultListener.onFail(2, "未获取有效token");
                                }
                            } else {
                                resultListener.onFail(1, errorMsg);
                            }
                        }
                    }

                    @Override
                    public void onFailureMainThread(Call call, IOException e) {
                        if (null != resultListener) {
                            resultListener.onFail(0, e.getMessage());
                        }
                        Y.y("JSONRequestonFailure:" + e.getMessage());
                    }
                });
        Ok3Util.getInstance().setBuilder(new OkHttpClient.Builder().connectTimeout(8000, TimeUnit.MILLISECONDS).retryOnConnectionFailure(false)).addToRequestQueueAsynchoronous(jsonRequest);
    }
}
